package ex05.pyrmont.valves;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.Request;
import org.apache.catalina.Response;
import org.apache.catalina.Valve;
import org.apache.catalina.ValveContext;
import org.apache.catalina.Contained;
import org.apache.catalina.Container;

/**
 * 这个 阀门 将作为一个拦截器, 处理 http 请求,  把 http 头打印出来;
 *
 * */
public class HeaderLoggerValveV5 implements Valve, Contained {

    protected Container container;

    public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException {

        // Pass this request on to the next valve in our pipeline
        valveContext.invokeNext(request, response);

        System.out.println("INFO  ex05.pyrmont.valves.HeaderLoggerValve    Header Logger Valve");
        ServletRequest servletRequest = request.getRequest();
        if (servletRequest instanceof HttpServletRequest) {

            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

            Enumeration headerNames = httpServletRequest.getHeaderNames();

            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement().toString();
                String headerValue = httpServletRequest.getHeader(headerName);
                System.out.println( "INFO    "  +   headerName + ":" + headerValue);
            }

        } else {

            System.out.println("ERROR   Not an HTTP Request");
        }

        System.out.println("------------------------------------");
    }

    public String getInfo() {
        return null;
    }

    public Container getContainer() {
        return container;
    }

    public void setContainer(Container container) {
        this.container = container;
    }
}
